<template>
    <el-card shadow="hover" class="management-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
            <el-form-item label="岗位名称">
                <el-input v-model="searchForm.title" placeholder="请输入岗位名称" clearable />
            </el-form-item>

            <el-form-item label="公司名称">
                <el-input v-model="searchForm.company" placeholder="请输入公司名称" clearable />
            </el-form-item>

            <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                    <el-option label="招聘中" value="招聘中" />
                    <el-option label="已结束" value="已结束" />
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
                <el-button @click="handleReset">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="header-actions">
            <el-button class="addbutton" type="primary" size="default" @click="showAddJobDialog">
                <el-icon class="el-icon--left">
                    <Plus />
                </el-icon>
                发布新岗位
            </el-button>
        </div>

        <el-table :data="tableData" border stripe highlight-current-row style="width: 100%"
            header-row-class-name="custom-header">
            <el-table-column prop="title" label="岗位名称" width="120" />
            <el-table-column prop="company" label="公司名称" width="130" />
            <el-table-column prop="requirements" label="岗位要求" width="223" show-overflow-tooltip />
            <el-table-column prop="resumeEmail" label="简历投递邮箱" width="180" show-overflow-tooltip />
            <el-table-column prop="publisherId" label="发布人ID" width="100" />
            <el-table-column prop="publishTime" label="发布时间" width="210" />
            <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                    <el-tag :type="row.status === '招聘中' ? 'success' : 'danger'" effect="dark">
                        {{ row.status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
                <template #default="{ row }">
                    <div class="action-buttons">
                        <el-button type="primary" size="small" plain @click="editJob(row)">
                            <el-icon>
                                <Edit />
                            </el-icon>
                        </el-button>
                        <el-button type="danger" size="small" plain @click="deleteJob(row.id)">
                            <el-icon>
                                <Delete />
                            </el-icon>
                        </el-button>
                        <el-button :type="row.status === '招聘中' ? 'warning' : 'success'" size="small" plain
                            @click="toggleStatus(row)">
                            {{ row.status === '招聘中' ? '结束' : '重启' }}
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
            <el-pagination background layout="prev, pager, next, sizes, total" :total="total" :page-size="pageSize"
                :current-page="currentPage" @current-change="handlePageChange" @size-change="handleSizeChange"
                class="mt-4" />
        </div>
    </el-card>

    <!-- 岗位编辑对话框 -->
    <el-dialog :title="isEditMode ? '编辑岗位' : '发布新岗位'" v-model="dialogVisible" width="40%" @closed="handleDialogClosed">
        <el-form :model="currentJob" :rules="rules" ref="jobForm" label-width="100px">
            <el-form-item label="岗位名称" prop="title">
                <el-input v-model="currentJob.title" placeholder="请输入岗位名称" />
            </el-form-item>
            <el-form-item label="公司名称" prop="company">
                <el-input v-model="currentJob.company" placeholder="请输入公司名称" />
            </el-form-item>
            <el-form-item label="岗位要求" prop="requirements">
                <el-input v-model="currentJob.requirements" type="textarea" :rows="4" placeholder="请输入岗位要求" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="currentJob.resumeEmail" placeholder="请输入简历投递邮箱" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-switch v-model="currentJob.status" active-value="招聘中" inactive-value="已结束" active-text="招聘中"
                    inactive-text="已结束" />
            </el-form-item>
            <el-form-item label="发布人ID" prop="publisherId" v-if="isEditMode">
                <el-input v-model="currentJob.publisherId" readonly />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import { get } from '@/request/request.js'

// 数据相关
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框相关
const dialogVisible = ref(false)
const isEditMode = ref(false)
const currentJobId = ref(null)
const currentJob = ref({
    id: null,
    title: '',
    company: '',
    requirements: '',
    resumeEmail: '',
    status: '招聘中',
    publisherId: ''
})

// 搜索表单数据
const searchForm = ref({
    title: '',
    company: '',
    status: ''
})

// 验证规则
const rules = {
    title: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
    company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
    requirements: [{ required: true, message: '请输入岗位要求', trigger: 'blur' }],
    email: [ // 新增邮箱验证规则
        { required: true, message: '请输入简历投递邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
    ],
}

// 获取数据
const fetchData = async (page = 1) => {
    try {
        const params = {
            ...searchForm.value,
            page: page,
            pageSize: pageSize.value
        }
        const response = await get('/api/getPosition', params)
        tableData.value = response.data.list
        total.value = response.data.total
    } catch (error) {
        ElMessage.error('获取岗位列表失败')
        console.error('Error:', error)
    }
}

// 搜索处理
const handleSearch = () => {
    currentPage.value = 1
    fetchData()
}

// 重置搜索
const handleReset = () => {
    searchForm.value = {
        title: '',
        company: '',
        status: ''
    }
    handleSearch()
}

// 新增对话框
const showAddJobDialog = () => {
    dialogVisible.value = true
    isEditMode.value = false
}

// 编辑岗位
const editJob = (job) => {
    currentJob.value = { ...job }
    dialogVisible.value = true
    isEditMode.value = true
    currentJobId.value = job.id
}

// 删除岗位
const deleteJob = async (id) => {
    try {
        await ElMessageBox.confirm('确定删除该岗位吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        await get(`/api/deletePosition/${id}`)
        ElMessage.success('删除成功')
        fetchData(currentPage.value)
    } catch (error) {
        ElMessage.error('删除失败')
        console.error('Error:', error)
    }
}

// 切换状态
const toggleStatus = async (row) => {
    try {
        const newStatus = row.status === '招聘中' ? '已结束' : '招聘中'
        currentJob.value = { ...row }
        const jobData = { ...currentJob.value }
        jobData.status = newStatus
        await get('/api/updatePosition', jobData)
        row.status = newStatus
        fetchData(currentPage.value)
        ElMessage.success('状态更新成功')
    } catch (error) {
        ElMessage.error('状态更新失败')
        console.error('Error:', error)
    }
}

// 提交表单
const handleSubmit = async () => {
    try {
        const jobData = { ...currentJob.value }
        jobData.publisherId = localStorage.getItem('loginUsername') // 发布人ID

        if (isEditMode.value) {
            jobData.id = currentJobId.value
            await get('/api/updatePosition', jobData)
            ElMessage.success('岗位信息更新成功')
        } else {
            await get('/api/addPosition', jobData)
            ElMessage.success('岗位发布成功')
        }
        dialogVisible.value = false
        fetchData(currentPage.value)
    } catch (error) {
        ElMessage.error(isEditMode.value ? '更新失败' : '发布失败')
        console.error('Error:', error)
    }
}

// 重置表单
const handleDialogClosed = () => {
    currentJob.value = {
        id: null,
        title: '',
        company: '',
        requirements: '',
        status: '招聘中',
        publisherId: ''
    }
}

// 分页处理
const handlePageChange = (page) => {
    currentPage.value = page
    fetchData(page)
}

// 每页显示数量变化
const handleSizeChange = (size) => {
    pageSize.value = size
    fetchData()
}

onMounted(() => {
    fetchData()
})
</script>

<style lang="scss" scoped>
/* 保持原有样式不变，仅修改类名对应部分 */
.addbutton {
    margin-bottom: 5px;
    float: right;
}

.search-form {
    width: 80%;
    float: left;

    .el-form-item {
        margin-right: 20px;
        margin-bottom: 10px;

        &:last-child {
            margin-right: 0;
        }
    }

    .el-input,
    .el-select,
    .el-date-editor {
        width: 220px;
    }
}

.management-card {
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

    :deep(.el-card__header) {
        border-bottom: 1px solid #ebeef5;
        background: linear-gradient(135deg, #f8f9fc, #ffffff);
    }
}

.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.pagination-wrapper {
    margin-top: 24px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-table) {
    .el-table__cell {
        padding: 12px 0;
    }
}
</style>